package com.app.controller.fileTransfer;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;


import java.io.IOException;
import java.net.URLEncoder;

/**
 * Created by Lichaojie on 2017/5/19. It's a beautiful day.
 */
public class UploadTest {


    public static void main(String[] args) throws IOException{
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone1());
//...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证，然后准备上传
        String accessKey = "C9VbYUI2FuUSf4OM_Fu20Obbtkl0e3RKKS1iO4ia";
        String secretKey = "WDVhFherV40lWeYgzg_Sn6igYN3x7_4D_V49luQf";
        String bucket = "qiniu-photo";
//如果是Windows情况下，格式是 D:\\qiniu\\test.png
        String localFilePath = "C:\\Users\\Lichaojie\\Desktop\\cutedog.png";
        //String localFilePath = "/home/qiniu/test.png";
//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        String ikey = "";
        String ihash = "";
        try {
            Response response = uploadManager.put(localFilePath, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            ikey = putRet.key;
            ihash = putRet.hash;
            System.out.println("key : " + ikey);
            System.out.println("hash : " + ihash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }

        String fileName = ikey;
        String domainOfBucket = "http://oopqx0v1l.bkt.clouddn.com";
        String encodedFileName = URLEncoder.encode(fileName, "utf-8");
        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        System.out.println(publicUrl);

        //long expireInSeconds = 3600;//1小时，可以自定义链接过期时间
        //String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        //String finalUrl = auth.privateDownloadUrl(publicUrl);
        //System.out.println(finalUrl);
    }




}
